/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package dao

import (
	"fmt"
	"prim-server/common"
	"prim-server/model"

	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
	"github.com/spf13/cast"
)

type BalanceDao struct {
	BaseDao
}

type IBalanceDao interface {
	SaveBalanceInfo(balanceAcount *model.Balance) error
	DeleteBalanceInfo(userId string) error
	UpdateBalanceInfo(balanceAcount *model.Balance) error
	GetBalanceInfo(queryParameter *common.QueryBalanceDetail) (balanceAcounts []*model.Balance, totalCount int, err error)
}

func GetBalanceDao() IBalanceDao {
	dao := &BalanceDao{}
	dao.Init()
	return dao
}

func (bd *BalanceDao) SaveBalanceInfo(balanceAcount *model.Balance) error {
	if balanceAcount == nil {
		return nil
	}
	_, err := bd.O.Insert(balanceAcount)
	if err != nil {
		return errors.Errorf("SaveBalanceInfo error: %v, userId: %s", err, balanceAcount.UserId)
	}
	return nil
}

func (bd *BalanceDao) DeleteBalanceInfo(userId string) error {
	if len(userId) == 0 {
		return nil
	}
	balanceAcount := new(model.Balance)
	balanceAcount.UserId = userId
	_, err := bd.O.Delete(balanceAcount, "user_id")
	if err != nil {
		return errors.Errorf("DeleteBalanceInfo error: %v, userId: %s", err, userId)
	}
	return nil
}
func (bd *BalanceDao) UpdateBalanceInfo(balanceAcount *model.Balance) error {
	if balanceAcount == nil {
		return nil
	}
	_, err := bd.O.Update(balanceAcount)
	if err != nil {
		return errors.Errorf("UpdateBalanceInfo error: %v, userId: %s", err, balanceAcount.UserId)
	}
	return nil
}
func (bd *BalanceDao) GetBalanceInfo(queryParameter *common.QueryBalanceDetail) (balanceAcounts []*model.Balance, totalCount int, err error) {
	if queryParameter == nil {
		return nil, 0, nil
	}
	recode := bd.O.QueryTable(&model.Balance{})
	finalCondition := orm.NewCondition()
	if len(queryParameter.UserId) > 0 {
		finalCondition = finalCondition.And("user_id__in", queryParameter.UserId)
	}
	if len(queryParameter.BalanceStatus) > 0 {
		finalCondition = finalCondition.And("balance_status__in", queryParameter.BalanceStatus)
	}
	offset, pageSize := bd.GetOffsetAndPageSize(queryParameter.Page, queryParameter.PageSize)
	recode = recode.SetCond(finalCondition)
	totalCount64, err := recode.Count()
	if err != nil {
		return nil, 0, errors.Errorf("GetBalanceInfo error:%v, userId: %s", err, fmt.Sprint(queryParameter.UserId))
	}
	totalCount = cast.ToInt(totalCount64)
	_, err = recode.Offset(offset).Limit(pageSize).All(&balanceAcounts)
	if err != nil {
		if err == orm.ErrNoRows {
			//not found
			return nil, 0, nil
		}
		//found error
		return nil, 0, errors.Errorf("GetBalanceInfo error: %v, userId: %s", err, fmt.Sprint(queryParameter.UserId))
	}
	return balanceAcounts, totalCount, nil
}
